// 封装倒计时函数
import dayjs from "dayjs";
import { ref, computed, onUnmounted } from "vue";

export const useCountDown = () => {
    let timer = null
    //1.响应数据
    const time = ref(0)
    // 格式化时间为 分秒
    const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
    // 倒计时
    // currentTime:初始化秒数
    const start = (currentTime) => {
        // 先清除之前的定时器（防止重复调用 start 导致多个定时器）
        if (timer) clearInterval(timer);

        time.value = currentTime
        timer = setInterval(() => {
            time.value--
            if (time.value <= 0) {
                clearInterval(timer); // 倒计时结束自动清除
            }
        }, 1000)
    }
    // 组件销毁消除定时器
    onUnmounted(() => {
        timer && clearInterval(timer)
    })
    return {
        formatTime,
        start
    }
}